<template>
    <div class="traceability-view">
        <!-- 标题栏 -->
        <div class="content-header">
            <div class="content-title">
                <span>溯源管理</span>
                <el-button type="primary" size="small" class="add-button" @click="handleAdd">
                    <el-icon>
                        <Plus />
                    </el-icon> 新增
                </el-button>
            </div>
            <!-- 查询条件 -->
            <div class="search-area">
                <el-form :inline="true" :model="queryParams" class="search-form">
                    <el-form-item label="商品名称">
                        <el-input v-model="queryParams.productName" placeholder="商品名称" clearable />
                    </el-form-item>
                    <el-form-item label="生产批次">
                        <el-input v-model="queryParams.productionBatch" placeholder="生产批次" clearable />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="fetchTraceabilityData">查询</el-button>
                        <el-button
                            @click="queryParams = { productName: '', productionBatch: '', shelfLife: '', productionLicense: '', manufacturer: '' }">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <!-- 表格内容 -->
        <el-table :data="tableData" style="width: 100%" border stripe v-loading="loading">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column prop="id" label="序号" width="80"></el-table-column>
            <el-table-column prop="name" label="商品名称" width="180"></el-table-column>
            <el-table-column prop="date" label="生产批次"></el-table-column>
            <el-table-column prop="days" label="保质期(天)" width="100"></el-table-column>
            <el-table-column prop="license" label="生产许可证号"></el-table-column>
            <el-table-column prop="company" label="生产企业"></el-table-column>
            <el-table-column label="操作" width="300">
                <template #default="scope">
                    <el-button size="small" type="primary" plain @click="handleDetail(scope.row)">
                        <el-icon>
                            <Edit />
                        </el-icon> 详情
                    </el-button>
                    <el-button size="small" type="warning" plain @click="handleEdit(scope.row)">
                        <el-icon>
                            <Edit />
                        </el-icon> 修改
                    </el-button>
                    <el-button size="small" type="primary" plain>
                        <el-icon>
                            <Document />
                        </el-icon> 导出
                    </el-button>
                    <el-button size="small" type="danger" plain @click="handleDelete(scope.row)">
                        <el-icon>
                            <Delete />
                        </el-icon> 删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
                :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <!-- 新增/修改对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '修改信息' : '基本信息'" width="600px">
            <div class="form-container">
                <el-form :model="formData" label-position="left" label-width="120px">
                    <el-form-item label="商品名称：" required>
                        <el-select v-model="formData.name" placeholder="请选择商品名称" class="form-input">
                            <el-option label="兔头（麻辣味）" value="兔头（麻辣味）" />
                            <el-option label="兔腿（小）" value="兔腿（小）" />
                            <el-option label="兔腿（大）" value="兔腿（大）" />
                            <el-option label="兔肉柱" value="兔肉柱" />
                            <el-option label="冷吃兔" value="冷吃兔" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="生产批次：" required>
                        <el-input v-model="formData.date" placeholder="请输入生产批次" class="form-input" />
                    </el-form-item>
                    <el-form-item label="保质期(天)：" required>
                        <el-input v-model="formData.days" placeholder="请输入保质期" class="form-input" />
                    </el-form-item>
                    <el-form-item label="生产许可证号：" required>
                        <el-input v-model="formData.license" placeholder="请输入生产许可证号" class="form-input" />
                    </el-form-item>
                    <el-form-item label="生产企业：" required>
                        <el-input v-model="formData.company" placeholder="请输入生产企业" class="form-input" />
                    </el-form-item>
                    <el-form-item label="封面图：">
                        <div class="upload-container">
                            <el-upload class="avatar-uploader" :action="imageService.getUploadUrl('traceability2212b')"
                                :headers="uploadHeaders" :show-file-list="false" :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSave">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { Delete, Edit, Plus, Document } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { traceabilityService } from '@/http/traceabilityService'
import { axiosInstance } from '@/http/axiosHelper'
import { useRouter } from 'vue-router'

// 路由器实例
const router = useRouter()

// 基础URL
const baseUrl = axiosInstance.defaults.baseURL

// 导入图片服务
import { imageService } from '@/http/imageService'

// 上传请求头
const uploadHeaders = imageService.getUploadHeaders()

// 对话框显示控制
const dialogVisible = ref(false)
const imageUrl = ref('')
const isEdit = ref(false) // 是否为编辑模式
const currentId = ref('') // 当前编辑的记录ID

// 表单数据
const formData = reactive({
    name: '',
    date: '',
    days: '',
    license: '',
    company: '',
    coverImage: ''
})

// 处理图片上传成功
const handleAvatarSuccess = (response: any, uploadFile: any) => {
    console.log('图片上传响应:', response) // 调试日志
    try {
        // 检查响应是否有效
        if (response && typeof response === 'object') {
            // 尝试获取图片URL
            if (response.imageUrl) {
                // 直接返回的是图片信息
                imageUrl.value = response.imageUrl
                formData.coverImage = response.imageUrl || response.imageUrl
                ElMessage.success('图片上传成功')
            } else if (response.data && response.data.imageUrl) {
                // 标准API响应格式
                imageUrl.value = response.data.imageUrl
                formData.coverImage = response.data.imageUrl || response.data.imageUrl
                ElMessage.success('图片上传成功')
            } else if (response.url || response.path) {
                // 其他可能的响应格式
                imageUrl.value = response.url || response.path
                formData.coverImage = response.imageUrl || response.url || response.path
                ElMessage.success('图片上传成功')
            } else {
                // 回退到本地预览
                if (uploadFile && uploadFile.raw) {
                    imageUrl.value = URL.createObjectURL(uploadFile.raw)
                    ElMessage.warning('图片已上传，但无法获取服务器路径')
                } else {
                    ElMessage.warning('图片上传状态未知')
                }
            }
        } else {
            // 响应格式不是对象
            ElMessage.warning('图片上传响应格式异常')
            if (uploadFile && uploadFile.raw) {
                imageUrl.value = URL.createObjectURL(uploadFile.raw)
            }
        }
    } catch (error) {
        console.error('处理图片上传响应出错:', error)
        ElMessage.error('处理图片上传响应时出错')
        // 尝试显示本地预览
        if (uploadFile && uploadFile.raw) {
            imageUrl.value = URL.createObjectURL(uploadFile.raw)
        }
    }
}

// 上传前验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // 检查文件类型
    if (!['image/jpeg', 'image/png', 'image/gif'].includes(rawFile.type)) {
        ElMessage.error('只能上传JPG/PNG/GIF格式的图片!')
        return false
    }
    // 检查文件大小
    if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('图片大小不能超过5MB!')
        return false
    }
    return true
}

// 保存表单
const handleSave = async () => {
    // 表单验证
    if (!formData.name) {
        ElMessage.error('请选择商品名称')
        return
    }
    if (!formData.date) {
        ElMessage.error('请输入生产批次')
        return
    }
    if (!formData.days) {
        ElMessage.error('请输入保质期')
        return
    }
    if (!formData.license) {
        ElMessage.error('请输入生产许可证号')
        return
    }
    if (!formData.company) {
        ElMessage.error('请输入生产企业')
        return
    }

    try {
        // 构建请求数据
        const traceabilityData = {
            productName: formData.name,
            productionBatch: formData.date,
            shelfLife: formData.days,
            productionLicense: formData.license,
            manufacturer: formData.company,
            coverImage: formData.coverImage
        }

        let response
        if (isEdit.value && currentId.value) {
            // 修改模式 - 调用更新API
            response = await traceabilityService.updateTraceabilityInfo(currentId.value, traceabilityData)
            if (response.success) {
                ElMessage.success('修改溯源信息成功')
            } else {
                ElMessage.error(response.message || '修改溯源信息失败')
            }
        } else {
            // 添加模式 - 调用添加API
            response = await traceabilityService.addTraceabilityInfo(traceabilityData)
            if (response.success) {
                ElMessage.success('添加溯源信息成功')
            } else {
                ElMessage.error(response.message || '添加溯源信息失败')
            }
        }

        if (response.success) {
            // 重置表单
            resetForm()
            // 关闭对话框
            dialogVisible.value = false
            // 刷新表格数据
            fetchTraceabilityData()
        }
    } catch (error) {
        console.error(isEdit.value ? '修改溯源信息失败:' : '添加溯源信息失败:', error)
        ElMessage.error(isEdit.value ? '修改溯源信息失败，请稍后再试' : '添加溯源信息失败，请稍后再试')
    }
}

// 重置表单
const resetForm = () => {
    formData.name = ''
    formData.date = ''
    formData.days = ''
    formData.license = ''
    formData.company = ''
    formData.coverImage = ''
    imageUrl.value = ''
    isEdit.value = false
    currentId.value = ''
}

// 处理修改按钮点击
const handleEdit = async (row: any) => {
    try {
        // 先重置表单
        resetForm()

        // 设置为编辑模式
        isEdit.value = true
        currentId.value = row.traceabilityId

        // 获取详细信息
        const response = await traceabilityService.getTraceabilityInfoById(row.traceabilityId)

        if (response.success && response.data) {
            // 填充表单数据
            formData.name = response.data.productName || ''
            formData.date = response.data.productionBatch || ''
            formData.days = response.data.shelfLife || ''
            formData.license = response.data.productionLicense || ''
            formData.company = response.data.manufacturer || ''
            formData.coverImage = response.data.coverImage || ''

            // 设置图片URL
            if (response.data.coverImage) {
                imageUrl.value = response.data.coverImage
            }

            // 显示对话框
            dialogVisible.value = true
        } else {
            ElMessage.error(response.message || '获取溯源信息详情失败')
        }
    } catch (error) {
        console.error('获取溯源信息详情失败:', error)
        ElMessage.error('获取溯源信息详情失败，请稍后再试')
    }
}

// 处理详情按钮点击
const handleDetail = async (row: any) => {
    // 跳转到详情页面，并传递溯源编号参数
    if (row && row.traceabilityId) {
        router.push(`/menu/traceability/detail/${row.traceabilityId}`)
    } else {
        ElMessage.error('无法获取溯源信息ID')
    }
}

// 处理新增按钮点击
const handleAdd = () => {
    // 重置表单
    resetForm()
    // 显示对话框
    dialogVisible.value = true
}

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页参数
const page = reactive({
    pageIndex: 1,
    pageSize: 5,
    totalCount: 0
})

// 查询参数
const queryParams = reactive({
    productName: '',
    productionBatch: '',
    shelfLife: '',
    productionLicense: '',
    manufacturer: ''
})

// 获取溯源信息数据
const fetchTraceabilityData = async () => {
    loading.value = true
    try {
        // 构建查询参数
        const params = {
            PageIndex: page.pageIndex,
            PageSize: page.pageSize,
            ProductName: queryParams.productName || undefined,
            ProductionBatch: queryParams.productionBatch || undefined,
            ShelfLife: queryParams.shelfLife || undefined,
            ProductionLicense: queryParams.productionLicense || undefined,
            Manufacturer: queryParams.manufacturer || undefined
        }
        // 使用封装的服务发送请求
        const response = await traceabilityService.queryTraceabilityInfo(params)

        if (response.success && response.data) {
            // 更新表格数据
            tableData.value = response.data.data.map((item: any, index: number) => ({
                id: index + 1,
                traceabilityId: item.traceabilityId,
                name: item.productName,
                date: item.productionBatch,
                days: item.shelfLife,
                license: item.productionLicense,
                company: item.manufacturer,
                coverImage: item.coverImage,
                createdBy: item.createdBy,
                createdTime: item.createdTime,
                lastModifiedBy: item.lastModifiedBy,
                lastModifiedTime: item.lastModifiedTime
            }))
            // 更新分页信息
            page.totalCount = response.data.totalCount
        } else {
            ElMessage.error(response.message || '获取溯源信息失败')
        }
    } catch (error) {
        console.error('获取溯源信息失败:', error)
        ElMessage.error('获取溯源信息失败，请稍后再试')
    } finally {
        loading.value = false
    }
}

// 处理分页变化
const handleSizeChange = (size: number) => {
    page.pageSize = size
    fetchTraceabilityData()
}

const handleCurrentChange = (current: number) => {
    page.pageIndex = current
    fetchTraceabilityData()
}

// 处理删除
const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm('确认删除该溯源信息吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        // 调用删除API
        if (row.traceabilityId) {
            const response = await traceabilityService.deleteTraceabilityInfo(row.traceabilityId)
            if (response.success) {
                ElMessage.success('删除成功')
                // 刷新表格数据
                fetchTraceabilityData()
            } else {
                ElMessage.error(response.message || '删除失败')
            }
        } else {
            ElMessage.error('无法获取溯源信息ID')
        }
    } catch (error) {
        // 用户取消删除
        console.log('取消删除')
    }
}

// 初始化加载数据
onMounted(() => {
    fetchTraceabilityData()
})

// 格式化百分比显示
const percentFormat = (percentage: number) => {
    return `${percentage}%`
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.traceability-view {
    padding: 10px;
}

.content-header {
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.content-title {
    font-size: 16px;
    font-weight: bold;
    display: flex;
    align-items: center;
    gap: 10px;
}

.add-button {
    margin-left: 15px;
}

/* 分页样式 */
.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.total-info {
    margin-right: 15px;
}

/* 表单样式 */
.form-container {
    padding: 0 20px;
}

.form-input {
    width: 100%;
}

/* 上传图片样式 */
.upload-container {
    display: flex;
    justify-content: flex-start;
}

.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
}

.avatar-uploader:hover {
    border-color: #409EFF;
}

.upload-placeholder {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
}

.upload-icon {
    font-size: 28px;
    color: #8c939d;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

/* 表单项样式 */
:deep(.el-form-item__label) {
    color: #f00;
    font-weight: normal;
}

:deep(.el-form-item__label::before) {
    content: "*";
    color: #f00;
    margin-right: 4px;
}

/* 搜索区域样式 */
.search-area {
    margin-bottom: 15px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
}
</style>